﻿using ACC.Business;
using ACC.Business.Process;
using ACC.Business.Stn;
using ACC.Data;
using ACC.Data.ACCLog;
using ACC.Data.Comm;
using ACC.Data.Line;
using ACC.Device;
using ACC.LineDevice.KukaPack;
using ACC.PrintTemplate;
using System;
using System.Collections.Generic;
using System.Data;

namespace Script
{
    /// <summary>
    /// 粘贴各类标签
    /// </summary>
    public class L1P12021 : StnProcessKukaPack
    {
        public L1P12021(StnRunningData data)
            : base(data)
        {
            materialTypeCount = 0;
        }
        protected override ACCDevice CreateDevice()
        {
            ACCDevice dev = base.CreateDevice();
            if (kukaSiemensDev != null)
            {
                kukaSiemensDev.DB190 = 800;
                kukaSiemensDev.DB190_Offset = 13000;
                kukaSiemensDev.DB192 = 80;
                kukaSiemensDev.DB192_PLC_Offset = 13066;

                kukaSiemensDev.DB193 = 800;
                kukaSiemensDev.DB193_PLC_Offset = 13034;
                kukaSiemensDev.DB193_ACC_Offset = 13068;
                kukaSiemensDev.DB194 = 800;
                kukaSiemensDev.DB194_PLC_Offset = 13034;
                kukaSiemensDev.DB194_PLC_Data_Offset = 13078;
            }

            return dev;

        }
        public override ACCCode ReadLoadParam(ACCDevice dev, out ACCDevice.LoadParam param)
        {
            ACCCode rs = base.ReadLoadParam(dev, out param);
            string orderNo;
            int planQty;
            GetWorkOrderByUnitSN(_lineData.Line, param.UnitSN, out orderNo, out planQty);
            if (!string.IsNullOrEmpty(orderNo))
            {
                var attrs = GetOrderAttributes(orderNo);
                if (attrs != null && attrs.ContainsKey("BOX_MODEL") && attrs.ContainsKey("BOX_TYPE"))
                {
                    _data.PartNo.Variables["boxmodel"] = attrs["BOX_MODEL"];
                    _data.PartNo.Variables["boxtype"] = attrs["BOX_TYPE"];
                }
                else
                {
                    return rs = ACCCode.UserDef_129; // 订单信息缺失，无法生成二维码
                }
            }
            return rs;
        }

        public override ACCCode SendLoadResult(ACCDevice dev, ACCDevice.LoadResult result)
        {
            ACCCode rs = base.SendLoadResult(dev, result);
            ProcessPrintLabel(dev);
            return rs;
        }

        public override ACCDevice.PrintResult ProcessPrintLabel(ACCDevice dev)
        {
            ACCDevice.PrintResult rs = new ACCDevice.PrintResult
            {
                ErrorCode = ACCCode.UserDef_150,
                ReturnCode = 150
            };
            if (_data.PartNo != null && _data.LastLoadUnit != null)
            {
                try
                {
                    logger.Debug("Begin print customer label");
                    string partno = _data.LastLoadUnit.PartNo;
                    string gbsn = _data.LastLoadUnit.GetUnitIDByIDName("GBSN").IDValue;
                    string time = System.DateTime.Now.ToString("yyyyMMdd");
                    // 标签2: 需要箱体类型和国标码
                    //        一维条形码: 国标码
                    // 标签3: 需要箱体型号，电芯批次, PartNo, 国标码
                    //        二位码: 电芯批次/Pack物料号/国标码/生产日期/数量
                    string cell = GetCellLotNo(_data.LastLoadUnit.UnitSN);
                    _data.PartNo.Variables["Cell"] = cell;
                    _data.PartNo.Variables["CustomerLabel"] = gbsn;
                    string CellCode = cell + "/" + partno + "/" + gbsn + "/" + time + "/" + "1";
                    _data.PartNo.Variables["CellCode"] = CellCode;
                    bool result = PrintTemplateProcess.DoPrint("CustomerLabelPrinter", null, _data.PartNo.BomCfg, "CustomerLabel", ref gbsn, logger);
                    bool result1 = PrintTemplateProcess.DoPrint("PackLabelPrinter", null, _data.PartNo.BomCfg, "PackLabel", ref CellCode, logger);
                    StnEventLog.Log(_data, StnLog.LogType.Event,
                        string.Format("Print label ({0}) and({1}),{2}", gbsn, CellCode, result ? "done" : "fail"));
                    logger.Debug("End print customer label");
                }
                catch (Exception e)
                {
                    StnEventLog.Log(_data, StnLog.LogType.Error,
                        string.Format("Excetion in print customer label process,message:{0}", e.Message));
                    return rs;
                }
            }
            else
            {
                logger.Debug("Print customer label fail,because partno is null");
            }
            return rs;
        }

        /// <summary>
        /// 根据Pack内部码获取电芯批次信息
        /// </summary>
        /// <param name="unitsn">Pack内部码</param>
        /// <returns>电芯批次</returns>
        private string GetCellLotNo(string unitsn)
        {
            string cellLot = "";
            List<string> lsMZ = new List<string>();
            string LotL = "", LotM = "", LotR = "";
            try
            {
                // 获取Pack绑定的三个模组码
                string sql = string.Format("SELECT ID_VALUE FROM [DBO].[ACC_UNITID] WHERE ID_NAME = '模组' AND LINE = 'PL02' AND UNITSN = '{0}'", unitsn);
                DataTable dt = DataManager.DBHelper.Query(sql);
                if (dt != null && dt.Rows.Count > 0)
                {
                    if (dt.Rows.Count >= 3)
                    {
                        sql = "SELECT DISTINCT LOTNO FROM [ACC_BATTERY_DATA] WHERE BARCODE IN ( SELECT ID_VALUE FROM [ACC_UNITID]  WHERE LINE = 'PL02_JT' AND ID_NAME = '电芯' AND UNITSN IN (SELECT ID_VALUE FROM [DBO].[ACC_UNITID] WHERE   LINE = 'PL02_MZ' AND ID_NAME = '模组基体' AND UNITSN = '{0}'))";
                        foreach (DataRow dr in dt.Rows)
                        {
                            string mzcode = dr["ID_VALUE"].ToString();      // 模组条码

                            // 分别获取三个模组各自对应的电芯批次号
                            dt = DataManager.DBHelper.Query(string.Format(sql, mzcode));
                            if (dt != null && dt.Rows.Count > 0)
                            {
                                if (mzcode.Substring(8, 1).ToUpper() == "A")        // 左
                                    LotL = dt.Rows[0]["LOTNO"].ToString();
                                if (mzcode.Substring(8, 1).ToUpper() == "B")        // 中
                                    LotM = dt.Rows[0]["LOTNO"].ToString();
                                if (mzcode.Substring(8, 1).ToUpper() == "C")        // 右
                                    LotR = dt.Rows[0]["LOTNO"].ToString();
                            }
                            else
                            {
                                logger.Error("get cell lot failed" + mzcode);
                            }
                        }

                        if (LotL == LotM && LotM == LotR)
                        {
                            // 如果左中右批次一致、直接返回该批次号
                            cellLot = LotR;
                        }
                        else
                        {
                            // 如果左中右批次不一致、则返回右模组的批次，并且在批次后面加上H
                            cellLot = LotR + "H";
                        }
                    }
                    else
                    {
                        logger.Error("get mz count error" + unitsn);
                    }
                }
                else
                {
                    logger.Error("get mz failed unitsn" + unitsn);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message + ex.StackTrace);
            }
            return cellLot;
        }
    }

}